// pages/folderpage/folderpage.js
import { request, fomatForCollect, upRequest, wxuuid,getTotalSize } from "../../utils/util.js"
const { $Message } = require('../../dist/base/index');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    allFileList:[], //所有文件
    currentPage:1,  //当前页码
    isNomore:false, //是否还有更多
    fileList: [], //文件列表
    visible1: false,  //控制开关
    isLoading: true,   //加载

    actions1: [       //普通actions
      {
        name: '从本地选择图片上传',
        icon: 'picture'
      },
      {
        name: '从会话中选择文件上传',
        icon: 'interactive'
      },
      {
        name: '新建文件夹',
        color: "#487ff8"
      },
    ],
    actions2: [       //收藏调用时进入
      {
        name: '新建收藏文件夹',
        color: "#487ff8"
      },
    ],
    actions3: [        //企业目录调用时进入
      {
        name: '从本地选择图片上传',
        icon: 'picture'
      },
      {
        name: '从会话中选择文件上传',
        icon: 'interactive'
      },
      
    ],
    classifyType: "",   //类型
    parent: "",         //父id
    homeType: "",       //来源的类型
    isNeedAdd:Boolean, //控制是否要加号
    collectProject:"",  //收藏要用的Projectid
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
   
    const name = options.name
    const key = options.key
    const classifyType = options.classifyType
    const homeType = options.homeType //收藏里用于看文件夹内内容
    const isNeedAdd = options.isNeedAdd//收藏内部是否需要添加按钮的
    const collectProject = options.collectProject
   
    wx.setNavigationBarTitle({
      title: name,
    })
    this.setData({
      ...this.data,
      classifyType: classifyType,
      parent: key,
      homeType: homeType,
      isNeedAdd:isNeedAdd,
      collectProject:collectProject
    })
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if(app.globalData.isNeedOnshow){
      this.setData({
        isNomore:false,
        currentPage:1
      })
      this.getFileList();
      wx.pageScrollTo({
        scrollTop:0,
        duration: 0,
      })
    }
    app.globalData.isNeedOnshow = true
   
   
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
   
    this.setData({
      isNomore:false,
      currentPage:1
    })
    this.getFileList();
  },
  /**
   * 上拉触底事件
   */
  onReachBottom: function (){
   
    const allFileList = [...this.data.allFileList]
  
    if(allFileList.length / 15 + 1 > this.data.currentPage){
      wx.showToast({
        title: '加载中',
        icon:'loading',
        duration:500
      })
      const newData = allFileList.slice(0,15 * this.data.currentPage)
      this.setData({
        fileList:newData,
        currentPage:this.data.currentPage + 1
      })
    }else{
      this.setData({
        isNomore:true
      })
    }
    
  },
  /**
 * 获取数据的封装
 */
  getFileList(showLoading) {
    
    const that = this
    if (showLoading == false) {
      that.setData({
        ...that.data,
        isLoading: true
      })
      let param = {}
      if (this.data.homeType) {
        param = {
          type: this.data.homeType,
          parent: this.data.parent,
          project:this.data.collectProject
        }
      } else {
        param = {
          type: this.data.classifyType,
          parent: this.data.parent
        }
      }
      request("GET", "/api/service/catalog", param).then(res => {
        const data = res.data.data
        const newData = fomatForCollect(data)
        const firstData = newData.slice(0,15)
        that.setData({
          fileList: firstData,
          currentPage:this.data.currentPage + 1,
          isLoading: false
        })//分开渲染，提升性能
        that.setData({
          allFileList:newData
        })
        wx.stopPullDownRefresh()

      })
      return;
    }
    
    let param = {}
    if (this.data.homeType) {
      param = {
        type: this.data.homeType,
        parent: this.data.parent,
        project:this.data.collectProject
      }
    } else {
      param = {
        type: this.data.classifyType,
        parent: this.data.parent
      }
    }
    request("GET", "/api/service/catalog", param).then(res => {
      const data = res.data.data
      const newData = fomatForCollect(data)
      const firstData = newData.slice(0,15)
      that.setData({
        fileList: firstData,
        currentPage:this.data.currentPage + 1,
        isLoading: false
      })
      that.setData({
        allFileList:newData
      })
      wx.stopPullDownRefresh()

    })
  },
  /**
     * 打开上啦菜单
     */
  add() {
    this.setData({
      visible1: true
    });
  },
  /**
  * 关闭上啦菜单
  */
  handleCancel1() {
    this.setData({
      visible1: false
    });
  },
  /**
   * 上啦框里的各个事件 (1)
   * @param {}} param0 
   */
  handleClickItem1({ detail }) {
    const that = this
    if (detail.index == 0) {
      wx.chooseImage({
        count: 9,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {

          // tempFilePath可以作为img标签的src属性显示图片
          const fileRes = res
          const file_size = getTotalSize(res)
          if(that.data.classifyType === "user"){
            const availableCapacity = wx.getStorageSync('availableCapacity') //获取可用容量
            if(file_size > availableCapacity){
              wx.showToast({
                title: '个人容量不足',
                icon:"none"
              })
              that.handleCancel1();
              return
            }
          }
          const tempFilePaths = res.tempFilePaths
          const length = tempFilePaths.length
          let successNum = 0
          const verify_file_hash = wxuuid()
          const param = {
            file_hash: verify_file_hash,
            file_catalog: that.data.parent,
            file_size:file_size
          }
          that.handleCancel1();
          request("POST", "/api/upload/verify/", param)
            .then(res => {
              if(res.data.detail){
                wx.showToast({
                  title: res.data.detail,
                  icon:'none'
                })
                return
              }
              if (res.statusCode === 200) {
                $Message({
                  content: `正在上传(0/${length})`,
                  duration: 999
                });
                for (let i = 0; i < length; i++) {
                  const chunk_hash = wxuuid() + "-0"
                  const file_hash = wxuuid()
                  const param = {
                    chunk_hash: chunk_hash,
                    file_hash: file_hash
                  }
                  const file_name = file_hash.split("-")[4]
                  const size = fileRes.tempFiles[i].size
                  upRequest("/api/upload/upload_chunk/", "chunk", tempFilePaths[i], param).then(res => {

                    if (res.statusCode === 200) {
                      const params = {
                        total_size: size,
                        file_catalog: that.data.parent,
                        file_hash: file_hash,
                        file_name: file_name + ".jpg",
                        version: 1.0
                      }
                      request("POST", "/api/upload/merge/", params).then(res => {
                        successNum = successNum + 1
                        $Message({
                          content: `正在上传(${successNum}/${length})`,
                          duration: 999
                        });
                        if (successNum === length) {
                          const showMsg = setTimeout(() => {
                            $Message({
                              content: "上传完成",
                              type: 'success',
                              duration: 2
                            });
                            that.getFileList();
                            clearTimeout(showMsg)
                          }, 500)
                        
                        }
                      })
                    }
                  }).catch(error => {

                  })
                }
              }
            })

        }
      })
    } else if (detail.index == 1) {
      wx.chooseMessageFile({
        count: 9,
        type: 'all',
        success(res) {
          const fileRes = res
          const file_size = getTotalSize(res)
          if(that.data.classifyType === "user"){
            const availableCapacity = wx.getStorageSync('availableCapacity') //获取可用容量
            if(file_size > availableCapacity){
              wx.showToast({
                title: '个人容量不足',
                icon:"none"
              })
              that.handleCancel1();
              return
            }
          }
          const tempFiles = res.tempFiles
          const length = tempFiles.length
          let successNum = 0
          const verify_file_hash = wxuuid()
          const param = {
            file_hash: verify_file_hash,
            file_catalog: that.data.parent,
            file_size:file_size
          }
          that.handleCancel1(); 
          request("POST", "/api/upload/verify/", param)
            .then(res => {
              if(res.data.detail){
                wx.showToast({
                  title: res.data.detail,
                  icon:'none'
                })
                return
              }
              if (res.statusCode === 200) {
                $Message({
                  content: `正在上传(0/${length})`,
                  duration: 999
                });
                
                for (let i = 0; i < length; i++) {
                  const chunk_hash = wxuuid() + "-0"
                  const file_hash = wxuuid()
                  const param = {
                    chunk_hash: chunk_hash,
                    file_hash: file_hash
                  }
                  const file_name = tempFiles[i].name
                  const size = tempFiles[i].size
                  upRequest("/api/upload/upload_chunk/", "chunk", tempFiles[i].path, param).then(res => {

                    if (res.statusCode === 200) {
                      const params = {
                        total_size: size,
                        file_catalog: that.data.parent,
                        file_hash: file_hash,
                        file_name: file_name,
                        version: 1.0
                      }
                      request("POST", "/api/upload/merge/", params).then(res => {
                        successNum = successNum + 1
                        $Message({
                          content: `正在上传(${successNum}/${length})`,
                          duration: 999
                        });
                        if (successNum === length) {
                          const showMsg = setTimeout(() => {
                            $Message({
                              content: "上传完成",
                              type: 'success',
                              duration: 2
                            });
                            that.getFileList();
                            clearTimeout(showMsg)
                          }, 500)
                        }
                      })
                    }
                  }).catch(error => {
                  
                  })
                }
              }
            })

        },
        fail() {

        }
      })
    } else {
      this.selectComponent("#inputModal").setShow()
    }
  },
  
  /**
   * 上啦框里的各个事件 (2)
   * @param {*} param0 
   */
  handleClickItem2({ detail }) {
    this.selectComponent("#inputModal").setShow()
  }, 
   /**
  * 测试用调用展示MSg
  * @param {*} e 
  */
 showMsg: function (e) {
  
   const mes = e.detail
   $Message({
     content: mes
   });
 },
   /**
   * 多选删除
   * @param {*} e 
   */
  multipleChoice(e){
    this.selectComponent("#halfScreen").showHalfScreen()
  },







})